package com.inspinia.upms.server.controller.upms;

import com.inspinia.base.cache.CacheUtil;
import com.inspinia.base.common.model.AjaxResult;
import com.inspinia.base.common.model.UserCacheKeys;
import com.inspinia.base.pagination.Pager;
import com.inspinia.base.util.CollectionUtil;
import com.inspinia.upms.common.model.Gender;
import com.inspinia.upms.common.model.role.UpmsRole;
import com.inspinia.upms.common.model.user.UpmsUser;
import com.inspinia.upms.common.model.user.UpmsUserStatus;
import com.inspinia.upms.common.model.user.UpmsUserVo;
import com.inspinia.upms.common.util.CacheClearUpUtil;
import com.inspinia.upms.rpc.api.UpmsRoleService;
import com.inspinia.upms.rpc.api.UpmsUserService;
import com.inspinia.upms.server.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.beans.PropertyEditorSupport;
import java.util.List;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/upms/user")
public class UpmsUserController extends BaseController {

    private String prefix = "upms/user/";

    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @InitBinder
    public void initBind(WebDataBinder binder) {
        binder.registerCustomEditor(UpmsUserStatus.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                UpmsUserStatus us = UpmsUserStatus.valueOf(Integer.valueOf(text));
                setValue(us);
            }
        });
        binder.registerCustomEditor(Gender.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                Gender gender = Gender.valueOf(Integer.valueOf(text));
                setValue(gender);
            }
        });

    }

    @Resource
    private UpmsRoleService roleService;

    @Resource
    private UpmsUserService userService;

    /**
     * 初始化页面
     *
     * @param model
     * @return
     */

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("userId",getPrincipalId());
        model.addAttribute("userStatus",UpmsUserStatus.values());
        return prefix + "user-pagination";
    }

    /**
     * 获取User数据显示在页面
     *
     * @param userVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public AjaxResult paging(UpmsUserVo userVo) {
        try {
            Pager<UpmsUserVo> pager = userService.findPage(userVo);
            AjaxResult ajaxResult = new AjaxResult(true, pager);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("查询用户列表失败", e);
            return new AjaxResult(false, e.getMessage());
        }
    }

    /**
     * 根据用户id获取用户信息
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public AjaxResult get(Long id) {
        UpmsUserVo user = userService.getVo(id);
        return new AjaxResult(user);
    }

    /**
     * 用户信息
     */
    @RequestMapping(value = "userInfo", method = RequestMethod.GET)
    public String userInfo(Model model) {
        UpmsUser user = userService.get(getPrincipalId());
        model.addAttribute("user",user);
        return prefix + "user-info";
    }

    /**
     * 创建用户初始化页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String toCreateHtml(Model model) {
        model.addAttribute("userStatus", UpmsUserStatus.values());
        model.addAttribute("gender",Gender.values());
        return prefix + "user-create";
    }

    /**
     * 创建用户
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public AjaxResult createUser(@Valid UpmsUser user,
                                 @RequestParam(value = "roleIds") List<Long> roleIds,
                                 @RequestParam(value = "deptIds") List<Long> deptIds,
                                 @RequestParam(value = "postIds", required = false) List<Long> postIds) {
        user.setStatus(UpmsUserStatus.OK);

        int insert = userService.insert(user, roleIds, deptIds, postIds);
        if (insert > 0) {
            return new AjaxResult(true,"添加用户成功");
        }
        return new AjaxResult(false, "添加用户失败");
    }

    @ResponseBody
    @RequestMapping(value = "findResourceIdsByRoleAndPost", method = RequestMethod.POST)
    public AjaxResult findResourceIdsByRoleAndPost(@RequestParam(value = "postIds[]", required = false) List<Long> postIds,
                                                   @RequestParam(value = "roleIds[]", required = false) List<Long> roleIds) {

        List<Long> resourceIds = userService.findResourceIdsByRoleAndPost(roleIds, postIds);
        return new AjaxResult(true, resourceIds);
    }

    /**
     * 检查手机号是否重复
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "validPhone", method = RequestMethod.POST)
    public boolean validPhone(String phone) {
        return !userService.validPhone(phone);
    }

    /**
     * 检查email是否重复
     *
     * @param email
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "validEmail", method = RequestMethod.POST)
    public boolean validEmail(String email) {
        return !userService.validEmail(email);
    }


    @RequestMapping(value = "goEdit", method = RequestMethod.GET)
    public String goEdit(Model model,Long id){
        UpmsUser user = userService.get(id);
        List<Long> roleIds = userService.findRoleIds(id);
        List<Long> deptIds = userService.findDeptIds(id);
        List<Long> postIds = userService.findPostIds(id);

        model.addAttribute("userStatus", UpmsUserStatus.values());
        model.addAttribute("gender",Gender.values());
        model.addAttribute("bean", user);
        model.addAttribute("roleIds", CollectionUtil.list2string(roleIds));
        model.addAttribute("postIds", CollectionUtil.list2string(postIds));
        model.addAttribute("deptIds", CollectionUtil.list2string(deptIds));
        return prefix + "user-edit";
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public AjaxResult edit(UpmsUser user,
                           @RequestParam(value = "roleIds") List<Long> roleIds,
                           @RequestParam(value = "deptIds") List<Long> deptIds,
                           @RequestParam(value = "postIds", required = false) List<Long> postIds) {
        int update = userService.update(user, roleIds, deptIds, postIds);
        if (update > 0) {
            CacheClearUpUtil.cleanUserResourceCache(user.getUserId());
            return new AjaxResult(true,"修改成功！");
        }
        return new AjaxResult(true,"修改用户失败！");
    }


    @ResponseBody
    @RequestMapping("getRolesOfUser")
    public AjaxResult getRolesOfUser(Long userId) {
        //获取用户的角色id
        List<Long> roleIds = userService.getRoleIds(userId);
        return new AjaxResult(true, roleIds);
    }

    /**
     * 获取所有的角色
     *
     * @return
     */
    @RequestMapping("getAllRoles")
    public String getAllRole(Model model) {
        List<UpmsRole> roleList = roleService.findAll();
        model.addAttribute("roles", roleList);
        return prefix + "assign-role";
    }


    /**
     * 给用户分配角色
     *
     * @param roleIds
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setRole", method = RequestMethod.POST)
    public AjaxResult setRole(@RequestParam(name = "roleIds[]", required = false, defaultValue = "") Long[] roleIds, Long userId) {
        userService.setRole(roleIds, userId);
        //清除用户已有权限的缓存
        CacheUtil.delete(UserCacheKeys.getUserMenuKey(userId));
        return new AjaxResult(true);
    }

    /**
     * 批量解冻和批量冻结
     *
     * @param userIds      用户ids
     * @param statusNumber 传入解冻和冻结枚举的code
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateStatus", method = RequestMethod.POST)
    public AjaxResult updateStatus(@RequestParam(name = "userIds[]", required = false, defaultValue = "") Long[] userIds, int statusNumber,String disableReason) {
        if (userIds.length != 0) {
            UpmsUserStatus status = UpmsUserStatus.valueOf(statusNumber);

            for (Long userId : userIds) {
                if (userId != 1) {
                    UpmsUser user = userService.get(userId);
                    user.setStatus(status);
                    user.setRemark(disableReason);
                    userService.update(user);
                }
            }
            return new AjaxResult(true,"操作成功");
        } else {
            return new AjaxResult(false, "请选择用户");
        }
    }

    /**
     * 删除用户相关的权限角色和用户
     * @param userIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delUser", method = RequestMethod.POST)
    public AjaxResult delUser(@RequestParam("userIds[]") List<Long> userIds){
        if (CollectionUtil.isNotEmpty(userIds)){
            userIds.stream().forEach(userId ->{
                userService.delete(userId);
            });
            return new AjaxResult(true,"操作成功");
        }
        return new AjaxResult(false,"操作失败");
    }
}